﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace PathFinder
{
    public partial class WalkInfoForm : Form
    {
        delegate void SetTextCallback(string text);
        private Thread thr;
        private Graph graph;

        public WalkInfoForm(Thread thr, Graph graph)
        {
            this.thr = thr;
            this.graph = graph;
            Size parentSize = MainForm.instance.Size;
            Point parentLocation = MainForm.instance.Location;
            InitializeComponent();
            this.Location = new Point((parentSize.Width - this.Width) / 2 + parentLocation.X, (parentSize.Height - this.Height) / 2 + parentLocation.Y);
            thr = new Thread(new ThreadStart(RunPercentage));
            thr.Start();
            this.ShowDialog();
        }

        private void RunPercentage()
        {
            while (this.DialogResult != DialogResult.Cancel)
            {
                try
                {
                    int percent = MainForm.instance.drawManager.Graph.PercentDone;
                    SetText(percent + " %");
                    if (percent == 100)
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                        break;
                    }
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
            }
        }

        private void SetText(string text)
        {
            if (this.PercentTextBox.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.PercentTextBox.Text = text;
            }
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.CancelingButton.Enabled = false;
            this.PercentTextBox.Visible = false;
            thr.Abort();
            int max = graph.GetThreadCount;
            while (graph.GetThreadCount != 0)
            {
                if (max < graph.GetThreadCount)
                    max = graph.GetThreadCount;
                richTextBox1.Text = "Aborting...\n\n" + graph.GetThreadCount + "/" + max + " threads remaining.";
                graph.Abort();
            }
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void WalkInfoForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(this.DialogResult != DialogResult.OK)
                CancelButton_Click(null, null);
        }

    }
}
